package com.ssn.dao;

import com.ssn.po.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface BlogRepository  extends JpaRepository<Blog,Long>, JpaSpecificationExecutor<Blog> {

    @Query("select b from Blog b where b.recommend = true and b.published = true")
    List<Blog> findTop(Pageable pageable);

    @Query("select b from Blog b where b.published = true")
    Page<Blog> findAllByPublished(Pageable pageable);

    @Query("select b from Blog b where b.published = true and (b.title like ?1 or b.content like ?1)")
    Page<Blog> findBlogBySearch(String search,Pageable pageable);

    @Modifying
    @Query("update Blog b set b.views = b.views+1 where b.id=?1")
    int updateViews(Long id);

    @Query("select b from Blog b where b.published = true")
    List<Blog> findAllByPublished();

    @Query("select function('date_format',b.createTime,'%Y') as year from Blog b where b.published = true group by year order by function('date_format',b.createTime,'%Y') DESC")
    List<String> findGroupYear();

    @Query("select b from Blog b where function('date_format',b.createTime,'%Y') = ?1 and b.published = true order by b.createTime DESC ")
    List<Blog> findByYear(String year);

    @Query("select function('count','*') from Blog b where b.published = true")
    Integer countBlogByPublished();
}
